package com.burstly.lib.service;

import android.content.Context;
import com.burstly.lib.constants.UriConstants;
import com.burstly.lib.persistance.ObjectSaveLoadHandler;
import com.burstly.lib.util.LoggerExt;
import com.burstly.lib.util.Utils;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;

public class ServerConfigurationService
{
  static final HashMap<String, Object> CONFIGURATION_DATA = new HashMap();
  static final LoggerExt LOG = LoggerExt.getInstance();
  static final Set<ConfigurationTaskWrapper> RECIPIENTS;
  static final String TAG = ServerConfigurationService.class.getSimpleName();
  static ThreadPoolExecutor sConfigurator;
  static ObjectSaveLoadHandler<HashMap<String, Object>> sFileHandler;
  static boolean sLoadConfig = true;
  static String sTestConfiguration;

  static
  {
    RECIPIENTS = new HashSet();
  }

  public static void addRecipient(IServerConfigurable paramIServerConfigurable)
  {
    if (paramIServerConfigurable != null);
    try
    {
      ConfigurationTaskWrapper localConfigurationTaskWrapper = new ConfigurationTaskWrapper(paramIServerConfigurable);
      LOG.logDebug(TAG, "Adding new recipient {0}", new Object[] { paramIServerConfigurable });
      if (!RECIPIENTS.add(localConfigurationTaskWrapper))
        LOG.logDebug(TAG, "This {0} recipient has already been added.", new Object[] { paramIServerConfigurable });
      enqueueConfiguration(localConfigurationTaskWrapper);
      return;
    }
    finally
    {
    }
  }

  private static void createExecutor()
  {
    try
    {
      if (sConfigurator == null)
      {
        sConfigurator = (ThreadPoolExecutor)Executors.newFixedThreadPool(1, new ThreadFactory()
        {
          public Thread newThread(Runnable paramAnonymousRunnable)
          {
            Thread localThread = new Thread(paramAnonymousRunnable);
            localThread.setName("Configurator's thread");
            return localThread;
          }
        });
        sConfigurator.setKeepAliveTime(300L, TimeUnit.SECONDS);
      }
      return;
    }
    finally
    {
      localObject = finally;
      throw localObject;
    }
  }

  private static void createFileHandler(Context paramContext, String paramString)
  {
    sFileHandler = new ObjectSaveLoadHandler(paramContext, "server_cfg_" + paramString);
  }

  private static Runnable createLoadCfgRunnable(final Context paramContext, String paramString)
  {
    return new Runnable()
    {
      private final ObjectSaveLoadHandler<HashMap<String, Object>> mFileHandler = ServerConfigurationService.sFileHandler;

      public void run()
      {
        try
        {
          Thread localThread = Thread.currentThread();
          String str1;
          if (ServerConfigurationService.sTestConfiguration == null)
          {
            if (localThread.isInterrupted())
            {
              ServerConfigurationService.LOG.logDebug(ServerConfigurationService.TAG, "Cancel configuration task", new Object[0]);
              return;
            }
            HttpHost localHttpHost = new HttpHost(UriConstants.getInstance().getPrimaryHost());
            ServerRequestBean localServerRequestBean = new ServerRequestBean();
            localServerRequestBean.setPublisher(this.val$publisherId);
            Utils.configureServerRequestBean(paramContext, localServerRequestBean);
            String str2 = Utils.toJson(localServerRequestBean);
            ServerConfigurationService.LOG.logDebug(ServerConfigurationService.TAG, "Data to post: {0}", new Object[] { str2 });
            HttpPost localHttpPost = new HttpPost(UriConstants.CONFIGURATION_URI);
            localHttpPost.setEntity(new StringEntity(str2, "UTF-8"));
            str1 = EntityUtils.toString(Utils.makeRequest(localHttpHost, localHttpPost).getEntity());
            ServerConfigurationService.LOG.logDebug(ServerConfigurationService.TAG, "Recieved configuration {0} from server.", new Object[] { str1 });
          }
          while ((!localThread.isInterrupted()) && (!"".equals(str1)))
          {
            ServerConfigurationService.CONFIGURATION_DATA.clear();
            ServerConfigurationService.CONFIGURATION_DATA.putAll(Utils.fromJson(str1));
            this.mFileHandler.save(ServerConfigurationService.CONFIGURATION_DATA);
            Iterator localIterator = ServerConfigurationService.getRecipientsSnapshot().iterator();
            while (localIterator.hasNext())
              ServerConfigurationService.safeApplyConfiguration((ServerConfigurationService.IServerConfigurable)localIterator.next());
            str1 = ServerConfigurationService.sTestConfiguration;
            ServerConfigurationService.LOG.logDebug(ServerConfigurationService.TAG, "Test configuration {0} applied.", new Object[] { str1 });
          }
          return;
        }
        catch (Exception localException)
        {
        }
      }
    };
  }

  public static void enableTestConfiguration(String paramString)
  {
    sTestConfiguration = paramString;
  }

  private static void enqueueConfiguration(ConfigurationTaskWrapper paramConfigurationTaskWrapper)
  {
    if ((sConfigurator != null) && (!sConfigurator.isShutdown()))
    {
      paramConfigurationTaskWrapper.setRunningTask(sConfigurator.submit(paramConfigurationTaskWrapper));
      LoggerExt localLoggerExt = LOG;
      String str = TAG;
      Object[] arrayOfObject = new Object[1];
      arrayOfObject[0] = Integer.valueOf(sConfigurator.getQueue().size());
      localLoggerExt.logDebug(str, "Working queue size {0}", arrayOfObject);
    }
  }

  static Set<ConfigurationTaskWrapper> getRecipientsSnapshot()
  {
    try
    {
      HashSet localHashSet = new HashSet(RECIPIENTS);
      return localHashSet;
    }
    finally
    {
      localObject = finally;
      throw localObject;
    }
  }

  private static ConfigurationTaskWrapper getWrapperByRecepient(IServerConfigurable paramIServerConfigurable)
  {
    Iterator localIterator = getRecipientsSnapshot().iterator();
    while (localIterator.hasNext())
    {
      ConfigurationTaskWrapper localConfigurationTaskWrapper = (ConfigurationTaskWrapper)localIterator.next();
      IServerConfigurable localIServerConfigurable = localConfigurationTaskWrapper.getRecepient();
      if ((localIServerConfigurable != null) && (localIServerConfigurable.equals(paramIServerConfigurable)))
        return localConfigurationTaskWrapper;
    }
    return null;
  }

  public static void initService(Context paramContext, String paramString)
  {
    try
    {
      createExecutor();
      createFileHandler(paramContext, paramString);
      final Runnable localRunnable = createLoadCfgRunnable(paramContext, paramString);
      ThreadPoolExecutor localThreadPoolExecutor = sConfigurator;
      localThreadPoolExecutor.execute(new Runnable()
      {
        private final ObjectSaveLoadHandler<HashMap<String, Object>> mFileHandler = ServerConfigurationService.sFileHandler;

        public void run()
        {
          if (ServerConfigurationService.sLoadConfig);
          for (HashMap localHashMap = (HashMap)this.mFileHandler.load(); localHashMap != null; localHashMap = null)
          {
            ServerConfigurationService.LOG.logDebug(ServerConfigurationService.TAG, "Loaded saved configuration {0} from fs.", new Object[] { localHashMap });
            ServerConfigurationService.CONFIGURATION_DATA.putAll(localHashMap);
            ServerConfigurationService.sLoadConfig = false;
            this.val$configurator.execute(localRunnable);
            return;
          }
          localRunnable.run();
        }
      });
      Iterator localIterator = getRecipientsSnapshot().iterator();
      while (localIterator.hasNext())
        enqueueConfiguration((ConfigurationTaskWrapper)localIterator.next());
    }
    finally
    {
    }
  }

  public static void removeRecipient(IServerConfigurable paramIServerConfigurable)
  {
    if (paramIServerConfigurable != null);
    try
    {
      if (sConfigurator != null)
      {
        ConfigurationTaskWrapper localConfigurationTaskWrapper = getWrapperByRecepient(paramIServerConfigurable);
        if (localConfigurationTaskWrapper != null)
        {
          LOG.logDebug(TAG, "Removing recipient {0}", new Object[] { paramIServerConfigurable });
          RECIPIENTS.remove(localConfigurationTaskWrapper);
          if (localConfigurationTaskWrapper.isScheduledInExecutor())
          {
            BlockingQueue localBlockingQueue = sConfigurator.getQueue();
            localConfigurationTaskWrapper.getRunningTask().cancel(true);
            LoggerExt localLoggerExt = LOG;
            String str = TAG;
            Object[] arrayOfObject = new Object[1];
            arrayOfObject[0] = Integer.valueOf(localBlockingQueue.size());
            localLoggerExt.logDebug(str, "Working queue size {0}", arrayOfObject);
          }
        }
      }
      return;
    }
    finally
    {
    }
  }

  private static void safeApplyConfiguration(IServerConfigurable paramIServerConfigurable)
  {
    if (paramIServerConfigurable != null);
    try
    {
      LOG.logInfo(TAG, "Running configuration for {0}", new Object[] { paramIServerConfigurable });
      paramIServerConfigurable.configure(CONFIGURATION_DATA);
      return;
    }
    catch (Exception localException)
    {
      LOG.logThrowable(TAG, localException);
    }
  }

  public static void shutdown()
  {
    try
    {
      if (sConfigurator != null)
      {
        ThreadPoolExecutor localThreadPoolExecutor = sConfigurator;
        sConfigurator = null;
        localThreadPoolExecutor.execute(new Runnable()
        {
          public void run()
          {
            Utils.lowerCurrentThreadPriority();
            ServerConfigurationService.LOG.logDebug(ServerConfigurationService.TAG, "Shutting down configurator service...", new Object[0]);
            this.val$configurationService.shutdownNow();
            ServerConfigurationService.sLoadConfig = true;
            Iterator localIterator = ServerConfigurationService.getRecipientsSnapshot().iterator();
            while (localIterator.hasNext())
            {
              ServerConfigurationService.ConfigurationTaskWrapper localConfigurationTaskWrapper = (ServerConfigurationService.ConfigurationTaskWrapper)localIterator.next();
              ServerConfigurationService.IServerConfigurable localIServerConfigurable = localConfigurationTaskWrapper.getRecepient();
              if (localIServerConfigurable == null)
                ServerConfigurationService.RECIPIENTS.remove(localConfigurationTaskWrapper);
              else if (!localIServerConfigurable.isConstantRecepient())
                ServerConfigurationService.RECIPIENTS.remove(localConfigurationTaskWrapper);
            }
            ServerConfigurationService.RECIPIENTS.clear();
          }
        });
      }
      return;
    }
    finally
    {
      localObject = finally;
      throw localObject;
    }
  }

  private static class ConfigurationTaskWrapper extends WeakReference<ServerConfigurationService.IServerConfigurable>
    implements ServerConfigurationService.IServerConfigurable, Runnable
  {
    private Future<?> mRunningTask;

    ConfigurationTaskWrapper(ServerConfigurationService.IServerConfigurable paramIServerConfigurable)
    {
      super();
    }

    public void configure(Map<String, Object> paramMap)
    {
      ServerConfigurationService.IServerConfigurable localIServerConfigurable = (ServerConfigurationService.IServerConfigurable)get();
      if (localIServerConfigurable != null)
        localIServerConfigurable.configure(paramMap);
    }

    public boolean equals(Object paramObject)
    {
      ServerConfigurationService.IServerConfigurable localIServerConfigurable1 = (ServerConfigurationService.IServerConfigurable)get();
      ServerConfigurationService.IServerConfigurable localIServerConfigurable2 = ((ConfigurationTaskWrapper)paramObject).getRecepient();
      if ((localIServerConfigurable1 != null) && (localIServerConfigurable2 != null))
        return localIServerConfigurable1.equals(localIServerConfigurable2);
      return super.equals(paramObject);
    }

    ServerConfigurationService.IServerConfigurable getRecepient()
    {
      return (ServerConfigurationService.IServerConfigurable)get();
    }

    Future<?> getRunningTask()
    {
      return this.mRunningTask;
    }

    public int hashCode()
    {
      ServerConfigurationService.IServerConfigurable localIServerConfigurable = (ServerConfigurationService.IServerConfigurable)get();
      if (localIServerConfigurable != null)
        return localIServerConfigurable.hashCode();
      return super.hashCode();
    }

    public boolean isConstantRecepient()
    {
      ServerConfigurationService.IServerConfigurable localIServerConfigurable = (ServerConfigurationService.IServerConfigurable)get();
      if (localIServerConfigurable != null)
        return localIServerConfigurable.isConstantRecepient();
      return false;
    }

    boolean isScheduledInExecutor()
    {
      return this.mRunningTask != null;
    }

    public void run()
    {
      ServerConfigurationService.IServerConfigurable localIServerConfigurable = (ServerConfigurationService.IServerConfigurable)get();
      if (localIServerConfigurable != null)
        if (this.mRunningTask == null)
          break label38;
      label38: for (boolean bool = this.mRunningTask.isCancelled(); !bool; bool = false)
      {
        ServerConfigurationService.safeApplyConfiguration(localIServerConfigurable);
        return;
      }
      ServerConfigurationService.LOG.logDebug(ServerConfigurationService.TAG, "Skipping config task for {0} due it was cancelled", new Object[] { localIServerConfigurable });
    }

    void setRunningTask(Future<?> paramFuture)
    {
      this.mRunningTask = paramFuture;
    }

    public String toString()
    {
      ServerConfigurationService.IServerConfigurable localIServerConfigurable = (ServerConfigurationService.IServerConfigurable)get();
      if (localIServerConfigurable != null)
        return localIServerConfigurable.toString();
      return "no recipient";
    }
  }

  public static abstract interface IServerConfigurable
  {
    public abstract void configure(Map<String, Object> paramMap);

    public abstract boolean isConstantRecepient();
  }
}

/* Location:           E:\android\Toy Defense 2_dex2jar.jar
 * Qualified Name:     com.burstly.lib.service.ServerConfigurationService
 * JD-Core Version:    0.6.2
 */